package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.File;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.config.SzConfig;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysFilesService;
import com.xiaoxu.intranetweb.util.FileUploadUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private ISysFilesService filesService;
    @PostMapping("/action")
    public SzResult action(){
        return SzResult.success("success");
    }
    //文件列表
    @GetMapping("/list")
    public SzResult getList(@RequestParam("connId") String connId, HttpServletResponse response, HttpServletRequest request) {
        QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
        sysFilesQueryWrapper.eq("CONN_ID", connId);
        List<SysFiles> fileList = filesService.list(sysFilesQueryWrapper);
        return SzResult.success(fileList);
    }
    //附件列表
    @GetMapping("/attachmentList")
    public SzResult getAttachmentList(@RequestParam("connId") String connId, HttpServletResponse response, HttpServletRequest request) {
        QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
        sysFilesQueryWrapper.eq("CONN_ID", connId+1);
        List<SysFiles> fileList = filesService.list(sysFilesQueryWrapper);
        return SzResult.success(fileList);
    }
    //上传文件
    @PostMapping("/upload")
    public SzResult upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request) throws IOException {
        String token = request.getHeader("Authorization");
        return filesService.upload(file,connId,token);
    }
    //上传附件
    @PostMapping("/uploadAttachment")
    public SzResult uploadAttachment(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request) throws IOException {
        String token = request.getHeader("Authorization");
        return filesService.upload(file,connId+1,token);
    }
    @GetMapping("/download")
    public void downloadFile(@RequestParam("id") String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            SysFiles sysFiles = filesService.getById(id);
            Path path = Paths.get(sysFiles.getFilePath());
            String fileName = sysFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }
    @GetMapping("/delete")
    public  SzResult deleteFile(String id) {
        SysFiles sysFiles = filesService.getById(id);
        File file = new File(sysFiles.getFilePath());
        if (file.exists()) {
            file.delete();
        }
        filesService.removeById(id);
        return SzResult.Success();
    }
}
